package com.example.demo.service;

import com.example.demo.model.Classes;
import com.example.demo.model.College;
import com.example.demo.model.Major;
import com.example.demo.model.Teacher;
import com.example.demo.model.User;
import com.example.demo.repository.ClassRepository;
import com.example.demo.repository.ClassStudentRepository;
import com.example.demo.repository.CollegeRepository;
import com.example.demo.repository.MajorRepository;
import com.example.demo.repository.TeacherRepository;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Service
public class ClassService {
    @Autowired
    private ClassRepository classRepository;
    
    @Autowired
    private ClassStudentRepository classStudentRepository;
    
    @Autowired
    private CollegeRepository collegeRepository;
    
    @Autowired
    private MajorRepository majorRepository;
    
    @Autowired
    private TeacherRepository teacherRepository;
    
    @Autowired
    private UserRepository userRepository;

    public Page<Classes> getAllClasses(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Classes> classPage = classRepository.findAll(pageable);
        // 为每个班级填充关联信息
        return classPage.map(this::populateClassInfo);
    }
    
    private Classes populateClassInfo(Classes classes) {
        // 填充专业和学院信息
        if (classes.getMajorId() != null) {
            Optional<Major> majorOpt = majorRepository.findById(classes.getMajorId());
            if (majorOpt.isPresent()) {
                Major major = majorOpt.get();
                classes.setMajorName(major.getName());
                
                // 填充学院信息
                if (major.getCollegeId() != null) {
                    Optional<College> collegeOpt = collegeRepository.findById(major.getCollegeId());
                    if (collegeOpt.isPresent()) {
                        classes.setCollegeName(collegeOpt.get().getName());
                    }
                }
            }
        }
        
        // 填充班主任信息
        if (classes.getHeadTeacherId() != null) {
            Optional<Teacher> teacherOpt = teacherRepository.findById(classes.getHeadTeacherId());
            if (teacherOpt.isPresent()) {
                Teacher teacher = teacherOpt.get();
                // 获取教师对应的用户信息以获取姓名
                Optional<User> userOpt = userRepository.findById(teacher.getUserId());
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    // 使用headTeacherName字段存储班主任姓名
                    classes.setHeadTeacherName(user.getRealName());
                }
            }
        }
        
        // 填充学生人数信息（从数据库查询实际的学生人数）
        int studentCount = classStudentRepository.findByClassId(classes.getId()).size();
        classes.setStudentCount(studentCount);
        
        return classes;
    }

    public Optional<Classes> getClassById(Long id) {
        Optional<Classes> classOpt = classRepository.findById(id);
        if (classOpt.isPresent()) {
            Classes classes = classOpt.get();
            populateClassInfo(classes);
            return Optional.of(classes);
        }
        return classOpt;
    }

    public Classes saveClass(Classes classes) {
        // 保存前更新学生人数
        int studentCount = classStudentRepository.findByClassId(classes.getId()).size();
        classes.setStudentCount(studentCount);
        return classRepository.save(classes);
    }

    public void deleteClass(Long id) {
        classRepository.deleteById(id);
    }

    public List<Classes> getClassesByName(String name) {
        return classRepository.findByNameContaining(name);
    }
    
    // 添加分页搜索方法
    public Page<Classes> searchClasses(String name, Classes.Status status, Classes.GraduationStatus graduationStatus, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        if (name != null && !name.isEmpty()) {
            name = "%" + name + "%";
        } else {
            name = null;
        }
        
        Page<Classes> result;
        if (name != null || status != null || graduationStatus != null) {
            result = classRepository.findByFilters(name, status, graduationStatus, pageable);
        } else {
            result = classRepository.findAll(pageable);
        }
        
        // 为每个班级填充关联信息
        return result.map(this::populateClassInfo);
    }

    // 根据专业ID获取班级的方法
    public List<Classes> getClassesByMajorId(Long majorId) {
        try {
            return classRepository.findByMajorId(majorId);
        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();
            // 返回空列表而不是抛出异常
            return List.of();
        }
    }
    
    // 检查班级是否有关联的学生
    public boolean hasStudents(Long classId) {
        // 检查class_students表中是否有该班级的学生关联记录
        return classStudentRepository.findByClassId(classId).size() > 0;
    }
    
    // 获取班级的学生人数
    public int getStudentCount(Long classId) {
        return classStudentRepository.findByClassId(classId).size();
    }
    
    // 同步所有班级的学生人数（用于修复数据不一致问题）
    public void syncAllClassStudentCounts() {
        List<Classes> allClasses = classRepository.findAll();
        for (Classes classes : allClasses) {
            int actualStudentCount = classStudentRepository.findByClassId(classes.getId()).size();
            if (actualStudentCount != classes.getStudentCount()) {  // 修复类型不匹配问题
                classes.setStudentCount(actualStudentCount);
                classRepository.save(classes);
            }
        }
    }
}